import React from 'react';
import classNames from 'classnames';
import ConfigProvider from '../config-provider';

type ButtonType = 'primary' | 'secondary' | 'ghost' | 'text' | 'link';
type ButtonSize = 'large' | 'middle' | 'small';
type ButtonIconPlace = 'left' | 'right';
type ButtonShape = 'circle' | 'round' | 'none';

interface ButtonProps {
  type?: ButtonType; // 按钮类型
  size?: ButtonSize; // 尺寸
  shape?: ButtonShape; // 按钮形状
  style?: Record<string, unknown>; // 内联样式
  className?: string; // 样式名
  prefixCls?: string; // 样式前缀
  loading?: boolean; // loading状态
  ghost?: boolean; // 是否幽灵属性
  disabled?: boolean; // 是否禁用
  bordered?: boolean; // 是否有边框
  icon?: React.ReactElement; // 图标
  iconPlace?: ButtonIconPlace; // 图标位置
  children?: React.ReactNode; // 子元素
  onClick?: React.MouseEventHandler<HTMLElement>; // 点击事件
}

export default function Button(props: ButtonProps) {
  const { getPrefixCls, prefixCls, size: contextSize } = React.useContext(ConfigProvider.ConfigContext);

  const {
    children,
    className,
    onClick,
    type = 'primary',
    size = contextSize,
    shape,
    ghost,
    loading,
    bordered = true,
    disabled,
    icon,
    prefixCls: customPrefixCls,
    ...rest
  } = props;

  const buttonRef = React.createRef<HTMLButtonElement>();
  const btnPrefixCls = getPrefixCls!(prefixCls, 'btn', customPrefixCls); // 按钮样式前缀

  const handleClick = (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement, MouseEvent>) => {
    onClick && onClick(e);
  };

  const btnClasses = classNames(btnPrefixCls, className, {
    [`${btnPrefixCls}-${type}`]: type, // 类型样式
    [`${btnPrefixCls}-size-${size}`]: size, // 尺寸样式
    [`${btnPrefixCls}-shape-${shape}`]: shape, // 圆或椭圆形状样式
    [`${btnPrefixCls}-no-border`]: !bordered, // 无边框样式
    [`${btnPrefixCls}-background-ghost`]: ghost && !disabled, // 幽灵样式
    [`${btnPrefixCls}-loading`]: loading, // 加载中样式
    [`${btnPrefixCls}-icon-only`]: !children && children !== 0 && icon
  });

  const iconElement = props.icon ? <span className={`${btnPrefixCls}-icon-wrapper`}>{React.cloneElement(props.icon, { loading, disabled, size })}</span> : '';

  return (
    <button ref={buttonRef} className={btnClasses} onClick={handleClick} disabled={disabled} {...rest}>
      {iconElement}
      {props.children}
    </button>
  );
}
